#include "napi/native_api.h"
#include <string>
#include "hilog/log.h"
#include "socketio_context.h"

namespace OHOS {
namespace SocketIO {
SocketIOContext::SocketIOContext(napi_env env)
    : env_(env), tsFunc_(nullptr)
    {}

//     SocketIOContext::~SocketIOContext()
//     {
//     if (tsFunc_ == nullptr) {
//         OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "LOG_TAG", "SocketIOContext::~SocketIOContext() tsFunc_ == nullptr");
//         return;
//     }
//     napi_status status = napi_release_threadsafe_function(tsFunc_, napi_tsfn_release);
//     OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "LOG_TAG", "SocketIOContext::~SocketIOContext() napi_tsfn_release");
//     }

void SocketIOContext::CreateTsFunction(napi_value func, const std::string &resourceName, void *context,
                                   napi_threadsafe_function_call_js callJsCallback)
{
    napi_value value = nullptr;
    napi_create_string_utf8(env_, resourceName.c_str(), strlen(resourceName.c_str()), &value);
    napi_create_threadsafe_function(env_, func, nullptr, value, 0, 1,
            nullptr, nullptr, context, callJsCallback, &tsFunc_);
}

void SocketIOContext::CallTsFunction(void *data)
{
    if (tsFunc_ == nullptr) {
        return;
    }
    napi_call_threadsafe_function(tsFunc_, data, napi_tsfn_blocking);
}

void SocketIOContext::ReleaseTsFunction()
{
    if (tsFunc_ == nullptr) {
        return;
    }
    napi_status status = napi_release_threadsafe_function(tsFunc_, napi_tsfn_release);
    if (status != napi_ok) {
        // LOG("AsyncMqtt release ts func error");
    }
    tsFunc_ = nullptr;
}


};
}